<?php
namespace app\index\controller;

use think\Request;
use think\Db;

use app\index\model\message as MessageModel;

class Message 
{
    public function addNewMessage($questionToken, $answerToken)
    {
        $note = new MessageModel;
        $note->questionToken = $questionToken;
        $note->answerToken = $answerToken;
        if ($note->save()) {
            return "add message success.";
        }
        else {
            return "add message fail.";
        }
    }
    public function getMessage(Request $request)
    {
        //获取请求参数
        $userToken = $request->param("userToken");
        $lastId = $request->param("lastId");
        $messageNum = $request->param("messageNum");
        
        $answerTab = "dcw_fastask_answer";
        $questionTab = "dcw_fastask_question";
        $messageTab = "dcw_fastask_message";
        $userTab = "dcw_fastask_user";
        
        $sql = "";
        if ($lastId == 0) {
            $sql = "SELECT 
                $questionTab.questionContent, 
                $questionTab.whenAsk,
                $answerTab.answerContent, 
                $answerTab.answerType,
                $answerTab.answerTime,
                $answerTab.recordLongTime,
                $userTab.userAvatar,
                $userTab.userName
                FROM $answerTab, $questionTab, $messageTab,$userTab
                WHERE $questionTab.askerToken='$userToken'
                AND $answerTab.questionToken=$questionTab.id
                AND $questionTab.id=$messageTab.questionToken
                AND $answerTab.id=$messageTab.answerToken
                AND $answerTab.answererToken=$userTab.userToken  
                ORDER BY $messageTab.id DESC LIMIT $messageNum
                ";
        }
        else {
            $sql = "SELECT 
                $questionTab.questionContent, 
                $questionTab.whenAsk,
                $answerTab.answerContent, 
                $answerTab.answerType,
                $answerTab.answerTime,
                $answerTab.recordLongTime,
                $userTab.userAvatar,
                $userTab.userName
                FROM $answerTab, $questionTab, $messageTab,$userTab
                WHERE $questionTab.askerToken='$userToken'
                AND $answerTab.questionToken=$questionTab.id
                AND $questionTab.id=$messageTab.questionToken
                AND $answerTab.id=$messageTab.answerToken
                AND $answerTab.answererToken=$userTab.userToken  
                AND $messageTab.id < $lastId
                ORDER BY $messageTab.id DESC LIMIT $messageNum
                ";
        }
        $allNote = Db::query($sql);

        //返回消息
        $JsonData = controller("index/JsonData");
        $json = $JsonData->getJsonData(0, "get message success.", $allNote);
        return $json;

    }
}